package cn.dkk.create_design.singleton.destroy;

import cn.dkk.create_design.singleton.hungery.staticMember.StaticHungerSingleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

/**
 * 单例模式的破坏演示
 */
public class DestroySingleton {
    public static void main(String[] args) throws Exception {

        // 1.反射破坏单例模式
        Class<StaticHungerSingleton> clazz = StaticHungerSingleton.class;
        Constructor<StaticHungerSingleton> declaredConstructor = clazz.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        StaticHungerSingleton singleton = declaredConstructor.newInstance();
        StaticHungerSingleton singleton1 = declaredConstructor.newInstance();
        System.out.println(singleton==singleton1);
        // 2.序列化破坏单例模式
        //writeObjectToFile();
        //System.out.println(readObjectFromFile()==readObjectFromFile());
    }
    public static void writeObjectToFile() throws Exception{
        StaticHungerSingleton singleton = StaticHungerSingleton.getSingleton();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("C:\\Users\\DKK\\Desktop\\1.txt"));
        objectOutputStream.writeObject(singleton);
        objectOutputStream.close();
    }

    public static StaticHungerSingleton readObjectFromFile() throws Exception{
        StaticHungerSingleton singleton = StaticHungerSingleton.getSingleton();
        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("C:\\Users\\DKK\\Desktop\\1.txt"));
        return (StaticHungerSingleton) inputStream.readObject();
    }
}
